#include "searchmp3dialog.h"
#include<QLabel>
#include<QLineEdit>
#include<QHBoxLayout>
#include<QPushButton>
#include<QUrl>
#include<QDesktopServices>
#include<QTableWidget>
#include<algorithm>
#include<QMessageBox>
#include"mainwindow.h"


SearchMp3Dialog::SearchMp3Dialog(QWidget *parent)
    :QWidget(parent)
{
    label = new QLabel(tr("Search"),this);
    lineEdit = new QLineEdit(this);
    connect(lineEdit,SIGNAL(textChanged(QString)),this,SLOT(innerSearch(QString)));
    ButtonOK = new QPushButton(tr("SearchOnline"),this);
    layout = new QHBoxLayout(this);
    layout->addWidget(label);
    layout->addWidget(lineEdit);
    layout->addWidget(ButtonOK);

    connect(ButtonOK,SIGNAL(clicked()),this,SLOT(search()));
    //connect(ButtonCancel,SIGNAL(clicked()),this,SLOT(close()));
}

void SearchMp3Dialog::search()
{
    if(!lineEdit->text().isEmpty()){
        url = new QUrl("http://www.google.cn/music/search?q="+lineEdit->text());
        QDesktopServices::openUrl(*url);
    }
    //this->close();  //!!!!
}

void SearchMp3Dialog::setTable(QTableWidget *Table)
{
    this->table = Table;
}

void SearchMp3Dialog::innerSearch(QString target)
{
    list.clear();
    for(int i=0 ; i < table->rowCount() ; i++){
        list.push_back(element(table->item(i,MainWindow::TITLE)->data(Qt::DisplayRole).toString()+
                               table->item(i,MainWindow::ARTIST)->data(Qt::DisplayRole).toString()+
                               table->item(i,MainWindow::ALBUM)->data(Qt::DisplayRole).toString()+
                               table->item(i,MainWindow::GENRE)->data(Qt::DisplayRole).toString()
                               ,i));
    }
    rowList.clear();
    for(QList<element>::iterator it = list.begin() ; it != list.end() ; it++){
        if(it->str.contains(target,Qt::CaseInsensitive))rowList.push_back(it->row);
    }
    for(int i=0 ; i < table->rowCount() ; i++){
        table->hideRow(i);
    }

    for(QVector<int>::iterator it = rowList.begin() ; it != rowList.end() ; it++){
        table->showRow(*it);
    }

    table->update();
}

bool SearchMp3Dialog::isSearching()
{
    if(lineEdit->text().isEmpty())
        return false;
    else
        return true;
}

QVector<int> SearchMp3Dialog::getRowList()
{
    return this->rowList;
}
